package com.com.athengzhi.springCloud.lb;

import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Package: com.com.athengzhi.springCloud.lb
 * @ClassName: MyLB
 * @Author: lhz
 * @CreateTime: 2023/4/22 13:46
 * @Description:
 */
@Component
public class MyLB implements LoadBalanced{
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    //获取服务提供者坐标也就是8001,8002在服务发现与调用里面的集合下标
    private final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0:current + 1;
        }while ( !this.atomicInteger.compareAndSet(current,next));
       return next;
    }

    @Override
    public ServiceInstance instance(List<ServiceInstance> instances) {
        int index = getAndIncrement() % instances.size();
        return instances.get(index);//通过下标获取服务
    }
}
